package com.marek1and.oracle;

import java.sql.Connection;
import java.sql.SQLException;

import oracle.jdbc.pool.OracleDataSource;

public class OracleJDBConnection {
	
	private volatile static OracleJDBConnection  jdbcConnection;
	private static Connection connection;
	
	private OracleJDBConnection() throws SQLException{
		registerOracleJDBCDriver();
		OracleDataSource dataSource = createOracleDataSource();
		connection = dataSource.getConnection();
//		connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","marek","mg100dfx");
	}
	
	public static final OracleJDBConnection getInstance() throws SQLException{
		if(jdbcConnection == null){
			synchronized(OracleJDBConnection.class){
				if(jdbcConnection == null)
					jdbcConnection = new OracleJDBConnection();
			}
		}
		
		return jdbcConnection;
	}
	
	private void registerOracleJDBCDriver() throws SQLException{
		try {
			Class.forName("oracle.jdbc.OracleDriver");
		} catch (ClassNotFoundException e) {
			throw new SQLException(e.getCause());
		}
	}
	
	private OracleDataSource createOracleDataSource() throws SQLException{
		OracleDataSource dataSource = new OracleDataSource();
		dataSource.setDatabaseName("XE");
		dataSource.setServerName("localhost");
		dataSource.setNetworkProtocol("tcp");
		dataSource.setUser("marek");
		dataSource.setPassword("mg100dfx");
		dataSource.setPortNumber(1521);
		dataSource.setDriverType("thin");
		return dataSource;
	}
	
	public Connection getConnection(){
		return connection;
	}
	
	public void closeConnection() throws SQLException{
		if(connection != null){
			connection.close();
		}
	}
}
